package com.example.producerandconsumer.blockingqueue;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class Producer implements Runnable {
    private final BlockingQueue<Data> queue;
    private final int num;

    public Producer(BlockingQueue<Data> queue, int num) {
        this.queue = queue;
        this.num = num;
    }

    @Override
    public void run() {
        System.out.println("生产者" + num + "开始生产！！！！！！！！！！！！！");
        Data data = null;
        Random random = new Random();
        while (true) {
            try {
                Thread.sleep(random.nextInt(1000));
                data = new Data("生产者" + num + "生产产品");
                if (!queue.offer(data, 1000, TimeUnit.MILLISECONDS)) {
                    System.out.println("生产者" + num + "生产失败！");
                } else {
                    System.out.println("生产者" + num + "生产了产品");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
